package com.edu.dao.impl;

import com.edu.dao.BaseDao;
import com.edu.dao.UserDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author:mx
 * @Date:2025/11/17-17:15:15
 */
public class UserDaoImpl implements UserDao {

    @Override
    public int update(int userId, double money) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = BaseDao.getConnection();
            String sql = "UPDATE user SET money = money + ? WHERE userId = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setDouble(1, money);
            pstmt.setInt(2, userId);
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        } finally {
            BaseDao.closeResources(conn, pstmt, null);
        }
    }

    @Override
    public void transferMoney(int userId1, int userId2, double money) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);//开启事务
            String sql = "UPDATE user SET money = money + ? WHERE userId = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setDouble(1, -money);
            pstmt.setInt(2, userId1);
            pstmt.executeUpdate();
            System.out.println(sql+"成功执行");
            System.out.println(1/0);
            String sql2 = "UPDATE user SET money = money + ? WHERE userId = ?";
            pstmt = conn.prepareStatement(sql2);
            pstmt.setDouble(1, +money);
            pstmt.setInt(2, userId2);
            pstmt.executeUpdate();

            conn.commit();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("事务回滚");
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            BaseDao.closeResources(conn, pstmt, null);
        }
    }
}
